<template>
  <div class="mainpg">
    <div class="main_spac1" style="padding-bottom: 5px">
      <div class="main_white padding10">
        <div class="mainor_form small-top">
          <el-form
            :inline="true"
            :model="form"
            class="demo-form-inline"
            ref="userListFrom"
            label-width="70px"
            id="form"
          >
            <el-form-item label="供应商：" prop="name">
              <el-input
                v-model.trim="form.name"
                placeholder="供应商名称/手机"
                clearable
                class="wid220"
              ></el-input>
            </el-form-item>
            <el-form-item label="状态：" prop="status">
              <el-select
                v-model.trim="form.status"
                placeholder="状态"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" :value="0"></el-option>
                <el-option
                  v-for="(item, key) in status_list"
                  :key="key"
                  :label="item"
                  :value="Number(key + 1)"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="类型：" prop="type">
              <el-select
                v-model.trim="form.type"
                placeholder="类型"
                class="wid220"
                @change="getArticleList"
              >
                <el-option label="所有" :value="0"></el-option>
                <el-option
                  v-for="(item, index) in type_list"
                  :key="item"
                  :label="item"
                  :value="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <div class="clearfix"></div> -->
            <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false">
            </MainFormBtn>
          </el-form>
        </div>

        <div class="main-controls-wrap">
          <div>
            <el-button type="primary" @click="(addedFormVisible = true), (type = 0)">新增供应商</el-button>
            <el-button @click="exportSupplier">导出</el-button>
          </div>
        </div>

        <div class="main_table" :style="{ height: borderHeight - 32 + 'px' }">
          <el-table
            ref="multipleTable"
            v-loading="listLoading"
            :data="list.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            :height="borderHeight - 32"
            :header-cell-class-name="this.$verticaline"
            :header-cell-style="tableHeightStyle"
            @header-dragend="changeTableWidth"
          >
            <el-table-column
              label="ID"
              prop="id"
              :width="tableWidth[hash + 'id'] || 60"
            />
            <el-table-column
              label="名称"
              prop="name"
              :width="tableWidth[hash + 'name']"
            />
            <el-table-column
              label="手机"
              prop="mobile"
              :width="tableWidth[hash + 'mobile']"
            />
            <el-table-column
              label="状态"
              prop="status"
              class-name="main_hei"
              :width="tableWidth[hash + 'status']"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  @change="
                    (val) => {
                      elswitch(val, scope.$index);
                    }
                  "
                  active-color="#03A98E"
                  active-text="开"
                  inactive-text="关"
                  class="mainor_switch"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column
              label="类型"
              prop="type"
              :width="tableWidth[hash + 'type']"
            >
              <template slot-scope="{ row }">
                <span :class="[row.type == 1 ? 'type1' : 'type2']">{{
                  type_list[row.type]
                }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="资质"
              prop="natural"
              :width="tableWidth[hash + 'natural']"
            >
              <template slot-scope="scope">
                <div class="demo-image__error mainor_im">
                  <el-image
                    fit="fill"
                    :src="scope.row.pic"
                    :preview-src-list="scope.row.imagseList"
                  >
                    <div slot="error" class="image-slot">
                      <img :src="puzzleImg" />
                    </div>
                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              prop="created_at"
              :width="tableWidth[hash + 'created_at']"
            >
              <template slot-scope="scope">{{
                parseTime(scope.row.created_at, "{y}-{m}-{d}")
              }}</template>
            </el-table-column>
            <el-table-column
              label="备注"
              prop="remark"
              :width="tableWidth[hash + 'remark']"
            />
            <el-table-column
              label="管理操作"
              align="center"
              prop="operate"
              :width="tableWidth[hash + 'operate'] || 200"
              class-name="main_hei"
            >
              <template slot-scope="scope">
                <!-- <router-link to="/purchasing/relation">
                  <el-link type="success">查看关系</el-link>
                </router-link> -->
                <el-link type="primary" @click="handleEdit(scope)"
                  >编辑</el-link
                >
                <el-link
                  type="danger"
                  @click="(id = scope.row.id), delet(scope.$index)"
                  >删除</el-link
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <div></div>
          <!-- 分页 -->
          <div class="main_page_r">
            <MainPagination
              :current-page="current.page"
              :page-sizes="[20, 30, 50, 100]"
              :page-size="limit"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 增加和编辑 -->
    <el-dialog
      :title="type == 1 ? '编辑供应商' : '新增供应商'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
      :visible.sync="addedFormVisible"
      class="main_dialog dialog600"
    >
      <el-form
        :inline="false"
        :model="info"
        :rules="rules"
        class="demo-form-inline form-message-mg"
        ref="userListFrom"
        label-width="120px"
      >
        <el-form-item label="名称：" prop="name">
          <el-input
            v-model.trim="info.name"
            placeholder="名称"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系人：" prop="contact">
          <el-input
            v-model.trim="info.contact"
            placeholder="联系人"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机：" prop="mobile">
          <el-input
            v-model.trim="info.mobile"
            placeholder="手机"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" :prop="type == 1 ? '' : 'password'">
          <el-input
            v-model.trim="info.password"
            show-password
            :placeholder="type == 1 ? '不填则不修改' : '填写6位以上的密码'"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>

        <el-form-item label="供应商地址：" prop="address">
          <el-input
            v-model.trim="info.address"
            placeholder="供应商地址"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model.trim="info.remark"
            placeholder="备注"
            clearable
            class="wid300"
          ></el-input>
        </el-form-item>
        <div class="demo">
          <el-form-item label="类型：" prop="status">
            <el-select
              v-model.trim="info.type"
              placeholder="类型"
              class="wid110"
            >
              <el-option label="普通供应" :value="1"></el-option>
              <el-option label="直供用户" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态：" prop="status" class="status_el">
            <el-switch
              v-model="info.status"
              active-color="#03A98E"
              active-text="开"
              inactive-text="关"
              class="mainor_switch"
            ></el-switch>
          </el-form-item>
        </div>
        <div class="upload_box">
          <span>资质：</span>
          <div class="right">
            <el-upload
              class="upload-demo"
              :action="uploadPath"
              :on-success="handSuccess"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              :on-error="handleError"
              :headers="{
                Authorization: getToken(),
              }"
              :file-list="fileList"
              :limit="3"
              list-type="picture"
            >
              <el-button size="small">上传图片</el-button>
              <div slot="tip" class="el-upload__tip">只能上传3张图片</div>
            </el-upload>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="(addedFormVisible = false), close()"
          >取 消</el-button
        >
        <el-button type="primary" @click="setupmine" v-repeatClick
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  supplier_index,
  supplier_add,
  supplier_edit,
  supplier_delete,
  supplier_confirmDelete,
  supplier_changeStatus,
  supplierExport,
} from "@/api/purchasing/purchasingSupplier";
import rules from "@/rules/purchasing/purchasingSupplier";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { parseTime, exportMethod } from "@/utils/index";
import { uploadPath, puzzleImg } from "@/api/currency";
import { mapGetters } from "vuex";
import MainPagination from '@/components/MainPagination'

export default {
  mixins: [mixins],
  components: { MainPagination },
  data() {
    return {
      // 时间
      parseTime,
      // 增加和编辑
      info: {
        name: "",
        mobile: "",
        password: "",
        contact: "",
        address: "",
        remark: "",
        status: false,
        type: 1,
        pics: "",
      },
      type: 0,
      id: 0,
      addedFormVisible: false,
      // 搜索
      form: {
        name: "",
        type: "",
        status: "",
      },
      // 验证
      rules,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      type_list: {},
      status_list: {},
      listLoading: false,
      // 上传凭证
      // 上传图片  组件列表
      fileList: [],
      // 临时储存
      imageList: [],
      uploadPath,
      puzzleImg,
    };
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  methods: {
    startGetting() {
      this.getArticleList();
    },
    // 关闭清空表单
    close() {
      this.info = {
        name: "",
        mobile: "",
        password: "",
        contact: "",
        address: "",
        remark: "",
        status: false,
        type: 1,
        pics: "",
      };
      this.fileList = [];
      this.imageList = [];
      this.$refs["userListFrom"].clearValidate();
    },
    // 查看价格开关
    elswitch(val, index) {
      this.supplier_changeStatus(val ? 1 : 0, index);
    },
    supplier_changeStatus(val, index) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {
                id: this.list.list.data[index].id,
                status: val,
              })
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.list.list.data[index].id, status: val }
      );
      supplier_changeStatus(data).then((res) => {
        if (res.errcode == 0) {
        } else {
          this.list.list.data[index].status = !(val == 1 ? true : false);
          this.$message.error(res.errmsg);
        }
      });
    },
    // 导出供应商
    exportSupplier() {
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      supplierExport(packApi(this.form)).then(res=> {
        exportMethod(res, "供应商列表", notify);
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.supplier_index();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.getArticleList();
    },
    // 编辑
    handleEdit(scope) {
      let row = scope.row;
      row.imagseList.map((e) => {
        this.fileList.push({
          url: e,
          name: e.substring(e.length - 18),
        });
      });
      this.imageList = row.imagseList
        ? JSON.parse(JSON.stringify(row.imagseList))
        : [];
      this.type = 1;
      this.id = row.id;
      this.info.name = row.name;
      this.info.mobile = row.mobile;
      this.info.password = "";
      this.info.contact = row.contact;
      this.info.address = row.address;
      this.info.remark = row.remark;
      this.info.status = row.status == 1 ? true : false;
      this.info.type = row.type;
      this.addedFormVisible = true;
    },
    // 删除
    delet(index) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: this.id }
      );
      this.$confirm("是否删除供应商?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          supplier_delete(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.list.list.data.splice(index, 1);
            } else if (res.errcode == 40030) {
              this.$confirm("是否强制删除供应商?", "提示", {
                confirmButtonText: "强制删除",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  supplier_confirmDelete(data).then((res) => {
                    if (res.errcode == 0) {
                      this.list.list.data.splice(index, 1);
                    }
                  });
                })
                .catch(() => {});
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 确认
    setupmine() {
      this.$refs["userListFrom"].validate((valid) => {
        if (valid) {
          if (this.type == 1) {
            if (this.info.password != "" && this.info.password.length < 6) {
              this.$message.error("密码为6位以上");
              return;
            }
          }
          this.type == 0 ? this.add() : this.edit();
        }
      });
    },
    // 新增保存
    add() {
      let info = JSON.parse(JSON.stringify(this.info));
      info.status = info.status ? 1 : 0;
      info.pics = this.imageList.join(",");
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, info)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        info
      );
      supplier_add(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "新增成功",
            type: "success",
          });
          this.current.page = 1;
          this.supplier_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 编辑保存
    edit() {
      let info = JSON.parse(JSON.stringify(this.info));
      info.pics = this.imageList.join(",");
      info.status = info.status ? 1 : 0;
      // console.log(info);
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, info, { id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        info,
        { id: this.id }
      );

      supplier_edit(data).then((res) => {
        this.addedFormVisible = false;
        if (res.errcode == 0) {
          this.$message({
            message: "编辑成功",
            type: "success",
          });
          this.supplier_index();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.supplier_index();
    },
    changePage(page) {
      this.current.page = page;
      this.supplier_index();
    },
    // 列表
    supplier_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.current,
        this.form
      );
      supplier_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.type_list = res.data.type_list;
          this.status_list = res.data.status_list;
          res.data.list.data.map((e) => {
            e.pic = "";
            e.imagseList = [];
            if (e.pics) {
              e.imagseList = e.pics.split(",");
              e.pic = e.imagseList[0];
            }
            e.status = e.status == 1 ? true : false;
          });
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    // 上传凭证
    // 上传图片-删除
    handleRemove(file) {
      const i = this.imageList.findIndex((item) => item == file.src);
      this.imageList.splice(i, 1);
    },
    handleError(err, file, fileList) {
      this.$message.error("上传失败");
    },
    // 上传图片-成功
    handSuccess(res, file, fileList) {
      console.log(this.imageList);
      this.imageList.push(res.data.src);
      console.log(this.imageList);
    },
    handleExceed(files, fileList) {
      this.$message.error("最多只能上传3张凭证");
    },
  },
  created() {
    this.getNumerical(160);
    // 列表
    this.supplier_index();
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 120px);
}
.reset {
  background-color: transparent;
  color: #1BA88E;
}
.demo {
  display: flex;
  align-items: center;
  /deep/ .status_el {
    .el-form-item__content {
      margin-left: 80px !important;
    }
    .el-form-item__label {
      width: 80px !important;
    }
  }
}
.upload_box {
  display: flex;
  align-items: flex-start;
  span {
    width: 120px;
    box-sizing: border-box;
    text-align: right;
    padding-right: 10px;
    justify-self: flex-end;
    margin-top: 10px;
  }
  /deep/.el-upload-list .el-upload-list--picture .el-upload-list__item {
    padding: 0px !important;
  }
  .upload-demo {
    width: 350px;
  }
}
.type1 {
  color: #03a98e;
}
.type2 {
  color: #f56c6c;
}
/deep/.main_table .el-table--small td .cell {
  height: auto;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
/deep/.el-table__body tr.current-row > td.el-table__cell,
.el-table__body tr.selection-row > td.el-table__cell {
  background: none;
}
</style>
